package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.RemindService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.oa.core.entity.com.Asset;
import com.fz.us.oa.core.entity.com.AssetMaintain;
import com.fz.us.oa.core.entity.com.AssetScrap;
import com.fz.us.oa.core.service.com.AssetMaintainService;
import com.fz.us.oa.core.service.com.AssetScrapService;
import com.fz.us.oa.core.service.com.AssetService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/26.
 */
@Controller
@RequestMapping(value = "/com/assetMaintain")
public class AssetMaintainController extends BaseController {

    private static final long serialVersionUID = 5432468333770535360L;
    @Autowired
    private AssetMaintainService assetMaintainService;
    @Autowired
    private AssetService assetService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private RemindService remindService;
    @Autowired
    private AssetScrapService assetScrapService;

    private Date dateApply;
    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    private SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    private DecimalFormat fnum = new DecimalFormat("##0.00");

    private Asset asset;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            AssetMaintain assetMaintain=assetMaintainService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("assetMaintain", assetMaintain);
        }
        model.addAttribute("user", user);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/assetmaintain_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            AssetMaintain assetMaintain=assetMaintainService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("stepNo", stepNo);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("assetMaintain", assetMaintain);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/assetmaintain_read";
    }

    /**
     * 保存Model数据
     */
    private AssetMaintain saveModel(User user, String keyId, String assetId, String name,
                                    String maintainReason, String maintainUnit, String maintainResult, String maintainMoney) throws ParseException {

        AssetMaintain assetMaintain = null;
        if (StringUtils.isBlank(keyId)) {
            assetMaintain = new AssetMaintain();
            assetMaintain.setCreater(user);
            assetMaintain.setCompany(user.getCompany());
        } else {
            assetMaintain = assetMaintainService.get(keyId);
        }

        if (StringUtils.isNotBlank(assetId)) {
            Asset asset = assetService.get(assetId);
            if (asset != null) {
                assetMaintain.setAsset(asset);
            }
        }

        if (StringUtils.isNotBlank(name)) {
            assetMaintain.setName(name);
        }

        if (StringUtils.isNotBlank(maintainReason)) {
            assetMaintain.setMaintainReason(maintainReason);
        }

        if (StringUtils.isNotBlank(maintainUnit)) {
            assetMaintain.setMaintainUnit(maintainUnit);
        }

        if (StringUtils.isNotBlank(maintainResult)) {
            assetMaintain.setMaintainResult(Integer.valueOf(maintainResult));
        }

        if (StringUtils.isNotBlank(maintainMoney)) {
            assetMaintain.setMaintainMoney(Double.valueOf(maintainMoney));
        }

        if (assetMaintain.getForm() == null) {
            assetMaintain.setForm("资产维修登记表");
        }

        return assetMaintain;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, @RequestParam(required = false) String keyId, String assetId, String name,
                       String maintainReason, String maintainUnit, String maintainResult, String maintainMoney) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetMaintain assetMaintain = saveModel(user,keyId,assetId,name,maintainReason,maintainUnit,maintainResult,maintainMoney);
        if(StringUtils.isNotEmpty(keyId)){
            assetMaintainService.update(assetMaintain);
            rMap.put("message", "更新成功");
        } else {
            assetMaintainService.save(assetMaintain, "com.fz.us.oa.core.entity.com.AssetMaintain");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     *提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, @RequestParam(required = false) String keyId, String assetId, String name,
                         String maintainReason, String maintainUnit, String maintainResult, String maintainMoney,
                         String curDutyId, String comment) throws ParseException{

        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetMaintain assetMaintain = saveModel(user,keyId,assetId,name,maintainReason,maintainUnit,maintainResult,maintainMoney);
        assetMaintain.setNumStatus(1);
        assetMaintain.setTxtStatus("流转中");

        Asset asset=assetMaintain.getAsset();
        asset.setTxtStatus("维修中");
        assetService.update(asset);

        if(asset.getUser()!=null){
            //发送提醒
            Remind remind = new Remind();
            remind.setUser(asset.getUser());
            remind.setBussinessKey("assetMaintain");
            remind.setKeyId(keyId);
            remind.setContent("您使用的资产进入维修状态，请查看");
            remindService.save(remind);
        }

        if (StringUtils.isNotEmpty(keyId)) {
            assetMaintainService.approve(assetMaintain, dutyService.get(curDutyId), comment);
        } else {
            assetMaintainService.commit(assetMaintain, "com.fz.us.oa.core.entity.com.AssetMaintain", dutyService.get(curDutyId));
        }

        if(assetMaintain.getProcessState().name().equals("Finished")){
            doFinished(assetMaintain,user);
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        AssetMaintain assetMaintain=assetMaintainService.get(keyId);
        assetMaintainService.approve(assetMaintain, dutyService.get(curDutyId), comment);

        if(assetMaintain.getProcessState().name().equals("Finished")){
            doFinished(assetMaintain,user);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(AssetMaintain assetMaintain,User user){
        assetMaintain.setDateApply(new Date());
        assetMaintain.setNumStatus(1);
        assetMaintain.setTxtStatus("维修完成");
        assetMaintainService.update(assetMaintain);

        if (assetMaintain.getMaintainResult()==0) {
            Asset asset = assetMaintain.getAsset();
            if(asset.getUser()==null){
                asset.setTxtStatus("空闲");
            }else{
                asset.setTxtStatus("使用中");
            }

            assetService.update(asset);

            //发送提醒
            Remind remind = new Remind();
            remind.setUser(assetMaintain.getAsset().getUser());
            remind.setBussinessKey("assetMaintain");
            remind.setKeyId(assetMaintain.getId());
            remind.setContent("您维修中的资产已经完成，请查看");
            remindService.save(remind);
        } else {
            AssetScrap assetScrap = new AssetScrap();
            Asset asset = assetMaintain.getAsset();
            assetScrap.setAsset(asset);
            assetScrap.setName(asset.getName());
            assetScrap.setCreater(user);
            assetScrap.setCompany(user.getCompany());
            assetScrap.setProcessState(FlowEnum.ProcessState.Finished);
            assetScrap.setNumStatus(0);
            assetScrap.setCreateType(1);
            assetScrap.setTxtStatus("已归档");
            assetScrap.setForm("资产报废登记表");
            assetScrapService.saveEntity(assetScrap);

            //发送提醒
            Remind remind = new Remind();
            remind.setUser(assetMaintain.getAsset().getUser());
            remind.setBussinessKey("assetMaintain");
            remind.setKeyId(assetMaintain.getId());
            remind.setContent("您维修中的资产无法修复，请查看");
            remindService.save(remind);
        }
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            AssetMaintain assetMaintain=assetMaintainService.get(keyId);
            assetMaintainService.back(assetMaintain, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            AssetMaintain assetMaintain=assetMaintainService.get(keyId);
            assetMaintainService.deny(assetMaintain, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    String viewtype, @RequestParam(required = false) String assetId,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);

        SearchResultPaging searchResult = null;

        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        rules.add(RuleHelper.eq("company", company));
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));

        if (!StringUtils.isEmpty(assetId)) {
            rules.add(RuleHelper.eq("asset.id", assetId));  // 所属一个资产下的使用登记表
        }

        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //维修登记
                rules.add(RuleHelper.eq("numStatus", 1));
                searchResult = assetMaintainService.paging(null,rules,order,
                        "com.fz.us.oa.core.entity.com.AssetMaintain", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},null);

            }else if(viewtype.equals("2")){
                //维修结果
                rules.add(RuleHelper.eq("numStatus", 1));
                searchResult = assetMaintainService.paging(null,rules,order,
                        "com.fz.us.oa.core.entity.com.AssetMaintain", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},null);

            }
        }else{
            //所有
            searchResult = assetMaintainService.paging(null,rules,order,
                    "com.fz.us.oa.core.entity.com.AssetMaintain", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},null);
        }

        List<AssetMaintain> assetMaintainList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(AssetMaintain assetMaintain: assetMaintainList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(assetMaintain.getId())?"":assetMaintain.getId());

            if(assetMaintain.getCreateTime() != null){
                dateApply = assetMaintain.getCreateTime();
                rMap.put("year", yearFormat.format(dateApply));   // 年份
                rMap.put("month", monthFormat.format(dateApply));   // 月份
                rMap.put("dateApply",dateFormat.format(dateApply));
            } else {
                rMap.put("year", "");   // 年份
                rMap.put("month", "");   // 月份
                rMap.put("dateApply","");
            }

            asset = assetMaintain.getAsset();
            if(asset!=null){
                rMap.put("assetNo", asset.getAssetNo());
            }

            rMap.put("name", assetMaintain.getName());
            rMap.put("maintainReason", assetMaintain.getMaintainReason());
            rMap.put("maintainResult", assetMaintain.getMaintainResult()==0?"维修完成":"无法修复");
            rMap.put("maintainMoney", fnum.format(assetMaintain.getMaintainMoney()));
//        rMap.put("txtStatus", assetMaintain.getTxtStatus());
//        rMap.put("processStateName", assetMaintain.getProcessState()==null?"": assetMaintain.getProcessState().value());
//        rMap.put("createTime", assetMaintain.getCreateTime()==null?"": DataUtil.DateTimeToString(assetMaintain.getCreateTime()));

            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }



}
